﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Web.Caching;
using System.Xml;

namespace PlexBB
{
    public class Language
    {
        private readonly string _path;
        private readonly List<string> _langFiles = new List<string>() { "Common" };
        private readonly Cache _cache;

        public Language(string name)
        {
            _path = Path.Combine(PlexBB.Current.GetResourceServerPath("Languages"), name); ;
            _cache = PlexBB.Current.Page.Cache;
        }

        public string this[string key]
        {
            get
            {
                string value;
                foreach (string file in _langFiles)
                {
                    if ((value = GetText(key, file)) != null)
                    {
                        return value;
                    }
                }
                return key;
            }
        }

        public void Require(string langFile)
        {
            if (!_langFiles.Contains(langFile))
            {
                _langFiles.Add(langFile);
            }
        }

        private string GetText(string key, string file)
        {
            string partFilename = Path.Combine(_path, file) + ".xml";
            string cacheItemKey = "plexbb_language_" + partFilename;

            //Dictionary<string, string> values = (Dictionary<string, string>)cache[cacheItemKey];
            //if (values == null)
            //{
            //    values = new Dictionary<string, string>();
            //    XmlDocument doc = new XmlDocument();
            //    doc.Load(partFilename);

            //    XmlNodeList nodes = doc.SelectNodes("/lang/node()");
            //    foreach (XmlElement element in nodes)
            //    {
            //        values.Add(element.Name, element.InnerText);
            //    }

            //    cache.Add(cacheItemKey, values, null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(1), CacheItemPriority.Normal, null);
            //}

            //string result;
            //return values.TryGetValue(key, out result) ? result : null;

            XmlDocument doc = (XmlDocument)_cache[cacheItemKey];
            if (doc == null)
            {
                // load part into cache
                doc = new XmlDocument();
                doc.Load(partFilename);
                _cache.Add(cacheItemKey, doc, null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(1), CacheItemPriority.Normal, null);
            }

            XmlNode node = doc.SelectSingleNode("/lang/" + key + "/text()");
            return node == null ? null : node.Value;
        }
    }
}
